﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zzcore.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Zzcore.Controllers
{
    public class TestController : BaseController
    {
        private readonly ILogger<TestController> _logger;
        public TestController(ILogger<TestController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        /// <summary>
        /// 哈哈测试测试
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IDictionary<string, Object>> IndexP()
        {
            // 获取当前角色的所有ID
            List<int> pmids = new(){ 15, 16 };
            foreach (var pmid in pmids)
            {
                await GetAllParentId(pmid);
            }

            // 该角色所有权限去重
            allPmids = allPmids.Distinct().ToList();
            JArray data = GetPermissionTreeData(0).Result;
            return RenderJson(data: data);
        }

        List<long> allPmids = new(); // 所有权限ID，后面要去重
        [NonAction]
        public async Task GetAllParentId(long id)
        {
            // 查询当前节点信息
            Permission permission = await _fsql.Select<Permission>().Where(m => m.Id == id).ToOneAsync();
            if (permission != null)
            {
                allPmids.Add(id);
                await GetAllParentId(permission.Pid);
            }
        }

        [NonAction]
        public async Task<JArray> GetPermissionTreeData(long pid)
        {
            JArray data = new();
            List<Permission> menus = await _fsql.Select<Permission>().Where(m => m.Pid == pid).Where(p => p.Hidden == 0).Where(p => allPmids.Contains(p.Id)).ToListAsync();
            if (menus != null && menus.Count > 0)
            {
                foreach (var menu in menus)
                {
                    JObject jo_menu = JObject.FromObject(menu);
                    jo_menu.Add("children", GetPermissionTreeData(menu.Id).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index()
        {
            // 建表
            await _fsql.Select<User>().ToListAsync();
            await _fsql.Select<Organizationinfo>().ToListAsync();
            await _fsql.Select<Permission>().ToListAsync();

            // 生成数据

            return RenderJson(data: DateTime.Now);
        }

        [HttpPost]
        public async Task<IActionResult> Ceshi()
        {
            JArray data = new();
            JObject jo = new();
            jo.Add("aaa", "哈哈");
            data.Add(jo);
            return new JsonResult(new { id = 1, data});
        }
    }
}
